package com.xiaoxin.experience.api.hls;

import com.xiaoxin.experience.api.hls.request.HlsPropertiesResponse;
import com.xiaoxin.experience.api.hls.request.HlsTaskListResponse;
import com.xiaoxin.experience.api.hls.request.CreateHlsTaskRequest;
import com.xiaoxin.experience.api.http.request.RemoveHlsTaskRequest;
import com.xiaoxin.experience.api.hls.request.RetryHlsTaskRequest;
import com.xiaoxin.experience.common.BaseResponse;
import com.xiaoxin.experience.service.hls.properties.HlsProperties;
import com.xiaoxin.experience.service.http.HttpService;
import com.xiaoxin.experience.util.DateUtil;
import com.xiaoxin.experience.util.FileUtil;
import com.xiaoxin.experience.util.StringUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author xiaoxin
 */
@RestController
@RequestMapping("/api/hls")
public class HlsController
{
    @Resource
    HttpService httpService;

    @Resource
    HlsProperties hlsProperties;

    private String lastName = "";

    private String lastUrl = "";

    private String lastDir = "";

    @RequestMapping("/properties")
    public HlsPropertiesResponse properties()
    {
        HlsPropertiesResponse response = new HlsPropertiesResponse();
        response.setLastName(lastName);
        response.setLastUrl(lastUrl);
        String defaultSaveDir =
                FileUtil.dirPathComplete(hlsProperties.getSaveDir()) + DateUtil.now(DateUtil.YMD_DASH);
        response.setSaveDir(StringUtil.isNotBlank(lastDir) ? lastDir : defaultSaveDir);
        response.setThreadCount(hlsProperties.getThreadCount());
        response.setRetryTimes(hlsProperties.getRetryTimes());
        return response;
    }

    @RequestMapping("/create/task")
    public BaseResponse createHlsTask(@RequestBody CreateHlsTaskRequest request)
    {
        lastName = request.getName();
        lastUrl = request.getDownloadUrl();
        lastDir = request.getSavePath();
        return httpService.createHlsTask(request);
    }

    @RequestMapping("/retry/task")
    public BaseResponse retryHlsTask(@RequestBody RetryHlsTaskRequest request)
    {
        return httpService.retryHlsTask(request);
    }

    @RequestMapping("/remove")
    public BaseResponse remove(@RequestBody RemoveHlsTaskRequest request)
    {
        return httpService.removeHlsTask(request);
    }

    @RequestMapping("/tasks")
    public HlsTaskListResponse getAllTasks()
    {
        return httpService.hlsTasks();
    }
}
